package com.imy.touch;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.os.SystemClock;

import com.imy.common.event.TakeScreenEvent;
import com.imy.common.root.RootTools;
import com.imy.common.util.ALog;
import com.imy.common.util.FileUtils;
import com.imy.common.util.ShellUtils;
import com.imy.common.util.ToastUtil;
import com.imy.touch.event.GeneralEvent;
import com.imy.touch.interfaces.CallAccessibilityService;
import com.imy.touch.root.client.LocalSocketClientTransceiver;
import com.imy.touch.root.client.SocketClient;
import com.imy.touch.root.touch.RootTouch;
import com.imy.touch.root.touch.ServerStartListener;

import org.greenrobot.eventbus.EventBus;

public class TouchCore {
    private static TouchCore gCore = new TouchCore();
    private static final String TAG = "TouchCore";
    public static final int ROOT = 0;
    public static final int NORMAL = 1;
    public static final int AUTO = 2;
    private int mode = AUTO;
    private RootTouch mRootTouch;

    public static TouchCore get() {
        return gCore;
    }

    public void setMode(int mode) {
        this.mode = mode;
    }

    public int getMode() {
        return mode;
    }

    private int retry = 3;
    private int currentRetry = 1;
    private SocketClient mClient;
    private Context mContext;

    public Context getContext() {
        return mContext;
    }

    public void init(final Context application,InitCallBack callBack) {
        this.mContext = application;
        boolean rootAvailable = RootTools.isRootAvailable();
        ALog.i("rootAvailable:"+rootAvailable);
        if (rootAvailable) {
            tryStartRootTouch(application,callBack);
        }else {
            callBack.onFail(false);
        }
    }

    public void tryStartRootTouch(Context application, final InitCallBack callBack) {
        mRootTouch = new RootTouch(application, new ServerStartListener() {
            @Override
            public void onSuccess() {
                ALog.ti("开启root服务成功");
                //链接
                SystemClock.sleep(1000); //开启服务需要时间
                startTouchClient(callBack);
            }

            @Override
            public void onFail() {
                ALog.ti("开启root服务失败");
            }
        });
    }

    private void startTouchClient(final InitCallBack callBack) {
        //需要延迟一下
        mClient = new SocketClient() {
            @Override
            public void onConnect(LocalSocketClientTransceiver transceiver) {
                ALog.ti("onConnect:");
            }

            @Override
            public void onConnectFailed() {
                ALog.ti("onConnectFailed:");
                mClient = null;
                tryToRetryClient(callBack);
            }

            @Override
            public void onReceive(LocalSocketClientTransceiver transceiver, String s) {
                ALog.ti("接收到消息:" + s);
                if (s.equals("ready")) {
                    EventBus.getDefault().post(GeneralEvent.build(GeneralEvent.ROOT_SERVER_START,
                            "RootTouch模式开启成功"));
                    if (callBack!=null){
                        callBack.onSuccess();
                    }
                } else {
                    //解析
                    String[] content = s.split(" ");
                    String action = content[0];
                    if (action.equals("t")) { //截图
                        String path = content[1];
                        String status = content[2];
                        String realPath = content[3];
                        TakeScreenEvent takeScreenEvent = new TakeScreenEvent();
                        takeScreenEvent.path = path;
                        //写入文件
                        String temp = "/data/local/tmp";
                        ShellUtils.execCommand("chmod 777 -R " + temp,true);
                        FileUtils.copyFile(realPath, path);
                        takeScreenEvent.isSuccess = status.equals("0");
                        if (listener != null) {
                            listener.TakScreen(takeScreenEvent);
                        }
                    }
                }
            }

            @Override
            public void onDisconnect(LocalSocketClientTransceiver transceiver) {
                mClient = null;
                ALog.ti("onDisconnect:");
                tryToRetryClient(callBack);

            }
        };
        mClient.connect();
    }

    private void tryToRetryClient(InitCallBack callBack) {
        if (currentRetry != retry) {
            try {
                Thread.sleep(1000);
                startTouchClient(callBack);
                currentRetry++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            callBack.onFail(true);
        }
    }

    public SocketClient getClient() {
        return mClient;
    }

    public void setCallAccessibilityService(CallAccessibilityService coreService) {
        this.mCallService=coreService;
    }
    public CallAccessibilityService getCallService(){
        return mCallService;
    }
    private CallAccessibilityService mCallService;
    public interface OnTakScreenListener {
        void TakScreen(TakeScreenEvent event);
    }

    public void setOnTakScreenListener(OnTakScreenListener listener) {
        this.listener = listener;
    }

    private OnTakScreenListener listener;

    public interface  InitCallBack{
        void onSuccess();
        void onFail(boolean isRoot);
    }


}
